import os
from datetime import datetime

from flask import request
from werkzeug.security import generate_password_hash, check_password_hash
import shutil

from src.init.init_path import DEFAULT_AVATAR_PATH
from src.model.UserModel import UserModel
from src.api.https import SUCCESS, FAIL
from src.init.init_db import db
from src.utils.aview_tool import AViewTool
from src.model.AritcleModel import ArticleModel


items = ["name", "email", "phone", "qq", "avatar", "info", "role"]
DEFAULT_PROFILE = {"age": 30, "name": "何Default", "gender": "男", "user_id": "XX123", "location": "陕西省石家庄市", "education": "中专",
                   "main_crop": "小麦", "soil_type": "褐土", "user_type": "小麦种植户", "challenges": ["水资源短缺", "极端天气"],
                   "data_usage": "基本不用", "device_usage": ["智能手机", "拖拉机"], "labor_source": "家庭+雇工",
                   "annual_income": "12-15万元", "crop_rotation": "小麦-玉米", "sale_channels": ["粮库", "加工厂"],
                   "farming_method": "半机械化", "record_keeping": "简单记录", "brand_awareness": "关注种子品牌",
                   "equipment_value": "18万元", "insurance_usage": "政策性保险", "operation_scale": 280,
                   "profile_summary": "陈麦丰是一位来自河北石家庄的经验丰富的小麦种植户，经营280"
                                      "亩土地，采用半机械化耕作方式，技术水平中等。他当前面临水资源短缺和极端天气的挑战，核心需求是节水灌溉技术和"
                                      "抗倒伏品种，同时关注土壤检测和市场预测。他主要通过微信和快手获取信息，偏好短视频教程和专家直播内容。长期目标是"
                                      "提高水资源利用效率和实现订单农业。他参与合作社，关注政策补贴，并采用喷灌、配方施肥和综合防治等现代农业技术。",
                   "secondary_crops": ["玉米"], "technical_level": "中级", "experience_years": 18, "financial_access": "信用社贷款",
                   "policy_awareness": "关注补贴", "development_goals": ["提高水效", "订单农业"], "irrigation_method": "喷灌",
                   "irrigation_source": "地下水", "content_preference": ["短视频教程", "专家直播"],
                   "cooperative_member": True, "ecommerce_activity": "偶尔网购", "learning_frequency": "4次/月",
                   "market_info_source": "合作社", "social_media_usage": ["微信", "快手"], "innovation_adoption": "观望",
                   "pest_control_method": "综合防治", "training_attendance": "每年3次", "fertilization_method": "配方施肥",
                   "main_knowledge_needs": ["节水灌溉", "抗倒伏品种"], "sustainability_focus": "中等", "annual_income_range_lakh": [12, 15],
                   "secondary_knowledge_needs": ["土壤检测", "市场预测"], "learning_frequency_monthly": 4.0}
USERNAME = 1
UID = 2


class UserTool:
    def __init__(self):
        self.username = None
        self.role = 0
        self.url = None

    def init(self, username: str, password: str, name: str) -> None:
        """
        :param username: 用户账号
        :param password: 密码
        :param name: 用户名
        """
        print(len(generate_password_hash(password, salt_length=8)))
        user = UserModel(username=username, name=name,
                         password=generate_password_hash(password, salt_length=8),
                         avatar="imgresource"+DEFAULT_AVATAR_PATH, profile=DEFAULT_PROFILE)
        db.session.add(user)
        db.session.commit()

    def check(self, username: str, password: str, name: str):
        """
        :param username: 用户账号
        :param password: 用户密码
        :param name: 用户名
        """
        if len(username) == 0 or len(password) == 0 or len(name) == 0:
            return "用户账号、用户密码和用户昵称不能为空"
        elif len(name) > 16:
            return "用户昵称过长"
        elif len(username) > 100:
            return "请输入正确的账号"
        elif len(password) < 8 or len(password) > 16:
            return "密码请保持在8-16位"
        elif UserModel.query.filter_by(username=username).first() is not None:
            return "当前账户已经被注册"

        return SUCCESS

    def check_password(self, username: str, password: str, type: int):
        """
        :param username: 用户账号 / uid
        :param password: 用户密码
        :param type: 选择使用username(1) / uid(2)
        """
        if type == USERNAME:
            user = UserModel.query.filter_by(username=username).first()
        else:
            user = UserModel.query.filter_by(uid=username).first()

        if user is None or not check_password_hash(user.password, password):
            return "用户名或密码错误"

        return user

    def delete(self, md_path: str) -> int:

        return SUCCESS

    def update(self, info: dict, uid: int) -> bool:
        """
        :param info: 更新信息字典
        :param uid: 用户id
        对用户信息进行更新
        """
        user = UserModel.query.filter_by(uid=uid).first()
        if not user:
            print("用户未找到")
            return False  # 如果用户不存在/uid过期，返回 False

        for item in items:
            if item in info and info[item] is not None and info[item] != getattr(user, item):
                print(f'item = {item}, info = {info[item]} ')
                setattr(user, item, info[item])
        db.session.commit()
        return True

    def list(self, uid: int) -> dict:
        """
        :param uid: 用户id
        根据用户id查找用户信息
        """
        user = UserModel.query.filter_by(uid=uid).first()
        if not user:
            return None

        info = {"uid": uid}

        for item in ["username", "createtime"] + items:
            info[item] = getattr(user, item)
            if item == "avatar":
                info[item] = "http://" + request.host + "/" + info[item]
            if item == "createtime":
                info[item] = info[item].strftime("%Y年%m月%d日 %H:%M:%S")
        return info

    def getProfile(self, uid: int):
        """
        :param uid: 用户id
        根据用户id查找用户画像,并增强点击和点赞历史
        """
        user = UserModel.query.filter_by(uid=uid).first()
        if not user:
            return None

        profile = getattr(user, "profile")
        if not profile:
            profile = {}

        aview_tool = AViewTool()

        # 获取浏览和点赞历史
        view_history = aview_tool.check_view(uid)
        like_history_aids = aview_tool.check_like(uid)

        # 处理浏览历史
        if view_history:
            viewed_aids = [item['aid'] for item in view_history[:5]]  # 取前5条
            viewed_articles = ArticleModel.query.filter(
                ArticleModel.aid.in_(viewed_aids)).all()
            viewed_titles = [article.title for article in viewed_articles]
            profile['viewed_articles_summary'] = f"最近浏览了以下文章：{', '.join(viewed_titles)}。"
            profile['recent_viewed_aids'] = viewed_aids
            print(profile['viewed_articles_summary'])
            
        # 处理点赞历史
        if like_history_aids:
            # 取前5条
            liked_articles = ArticleModel.query.filter(
                ArticleModel.aid.in_(like_history_aids[:5])).all()
            liked_titles = [article.title for article in liked_articles]
            profile['liked_articles_summary'] = f"最近点赞了以下文章：{', '.join(liked_titles)}。"
            profile['recent_liked_aids'] = like_history_aids[:5]
            print(profile['liked_articles_summary'])
            
        return profile
